﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Tsingda.CacheModule
{
    public class HashTable
    {
        private static Hashtable ht = new Hashtable();

        public Hashtable CacheTable
        {
            get { return ht; }
        }
        public static void Add(string key, object memo, int minutes)
        {
            if (!ht.ContainsKey(CreateKey(key)))
            {
                ht.Add(CreateKey(key), memo);
            }
        }

        public static bool Container(string key)
        {
            return ht.ContainsKey(CreateKey(key));
        }

        public static void Remove(string key)
        {
            if (ht.ContainsKey(CreateKey(key)))
                ht.Remove(CreateKey(key));
        }

        public static string Get(string key)
        {
            string k = CreateKey(key);
            if (ht.ContainsKey(k))
            {
                return ht[CreateKey(key)].ToString() + "<!-- From Cache{" + k + "} -->";
            }
            else
                return "no content for this url from CacheHttpModule!";
        }

        /// <summary>
        /// 对URL路径做MD5编码,作为缓存的 Key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string CreateKey(string key)
        {
            return EncryptString(key.Trim());
        }


        private static string EncryptString(string str)
        {
            byte[] buffer = System.Security.Cryptography.MD5.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(str));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < buffer.Length; i++)
            {
                builder.Append(buffer[i].ToString("X2"));
            }
            return builder.ToString();
        }

    }
}
